<template>
  <!-- 村民功能列表 -->
  <view>
    <!-- <text>传递过来的随货同行单id: {{ product }}</text> -->
    <view class="container">
      <view class="info-card">
        <view class="item-field">
          <text class="label">随货同行单编号:</text>
          <text class="value">{{ suihuo.outOrderId }}</text>
        </view>
        <view class="item-field">
          <text class="label">发货时间:</text>
          <text class="value">{{ formatTimestamp(suihuo.createTime) }}</text>
        </view>
      </view>
      <!-- 子表数据列表 -->
      <view v-for="(item, index) in suihuozi" :key="index">
        <view class="info-card horizontal">
          <view class="item-field">
            <text class="label">产品名称:</text>
            <text class="value">{{ item.productName }}</text>
          </view>
          <view class="item-field">
            <text class="label">产品批次:</text>
            <text class="value">{{ item.batch }}</text>
          </view>
          <view class="item-field">
            <text class="label">产品规格:</text>
            <text class="value">{{ item.productStandards }}</text>
          </view>
          <view class="item-field">
            <text class="label">数量:</text>
            <text class="value">{{ item.count }}</text>
          </view>
          <view class="item-field">
            <text class="label">单价:</text>
            <text class="value">{{ item.productPurchasePrice }}</text>
          </view>
          <view class="item-field">
            <text class="label">总价:</text>
            <text class="value">{{ item.totalPrice }}</text>
          </view>
        </view>
        <view>
          <!-- 入库数量输入框 -->
          <view class="item-field stock-in-container" style="margin-top: 10px; margin-left: 0;">
            <text class="label">入库数量:</text>
            <input
              type="number"
              :value="item.inCount"
              @input="handleStockInQuantityInput($event, index)"
              placeholder="请输入入库数量"
              style="margin-left: 10px;"
            />
          </view>
          <!-- 当入库数量不等于发货数量时显示备注输入框 -->
          <view class="item-field remark-container" style="margin-top: 10px;">
            <text class="label">备注:</text>
            <input
              type="text"
              v-model="item.remark"
              placeholder="请输入备注"
              style="margin-left: 10px;"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- 确定按钮 -->
    <view class="button-container">
      <button @click="handleConfirm">确定</button>
    </view>
  </view>
</template>

<script>
import * as SupplierSendOrderApi from '@/api/suppliersendorder/inde.js'; // 随货同行单
import * as SupplierSendOrderItemApi from '@/api/suppliersendorderitem/index.js'; // 随货同行单项
import * as PurPurchaseOrderApi from '@/api/purpurchaseorder/index.js'; // 订单表
import * as PurchaseInOrderApi from '@/api/purchaseinorder/index.js'; // 入库审核单



// 获得ERP 随货同行单项
export function getSupplierSendOrderItem(id) {
  return request({
    url: '/erp/supplier-send-order-item/get?id=' + id,
    method: 'get'
  })
}








export default {
  data() {
    return {
      product: '', // 存储扫码传递过来的随货同行单
      suihuozi: [],
      suihuo: {},
      subTableData: [] // 新增变量存储订单表子表数据
    };
  },
  onLoad(options) {
    console.log('传递过来的参数', options.data);
    this.product = options.data;
    console.log(this.product);
    this.getList(); 
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        const ress = await SupplierSendOrderApi.getSupplierSendOrder(this.product);
        this.suihuo = ress.data;
        console.log('主表数据', this.suihuo);
        const purchaseOrderId = this.suihuo.purchaseOrderId; // 提取purchaseOrderId
        console.log("puerchaseOrderId",purchaseOrderId)
        this.subTableData = await this.getOrderSubTableData(purchaseOrderId); // 调用方法查询子表数据
        const res = await SupplierSendOrderApi.getSupplierSendOrderItemListByOutOrderId(this.product);
        this.suihuozi = res.data;
        console.log('子表数据', this.suihuozi);
        // 初始化入库数量为0
        this.suihuozi.forEach(item => {
          item.inCount = item.count; // 初始化inCount为发货数量
          item.remark = ''; // 初始化备注
        });
      } finally {
        // 这里可以添加一些清理代码，如果需要的话
      }
    },
    // 新方法：通过purchaseOrderId查询订单表的子表数据
    async getOrderSubTableData(purchaseOrderId) {
      try {
        const subTableData = await PurPurchaseOrderApi.getPurPurchaseOrderItemListByPurchaseOrderId(purchaseOrderId); 
        console.log('订单表子表数据', subTableData);
        return subTableData.data;
      } catch (error) {
        console.error('查询订单表子表数据失败:', error);
        return [];
      }
    },
    // 时间戳转换方法
    formatTimestamp(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // // 当前年月日时分秒毫秒,当做入库批次使用
    // getCurrentDateTime() {
    //   const now = new Date();
    //   const year = now.getFullYear();
    //   const month = String(now.getMonth() + 1).padStart(2, '0');
    //   const day = String(now.getDate()).padStart(2, '0');
    //   const hours = String(now.getHours()).padStart(2, '0');
    //   const minutes = String(now.getMinutes()).padStart(2, '0');
    //   const seconds = String(now.getSeconds()).padStart(2, '0');
    //   const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
    //   return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
    // },
    // formatDate() {
    //   const date = new Date();
    //   const year = date.getFullYear();
    //   const month = String(date.getMonth() + 1).padStart(2, '0');
    //   const day = String(date.getDate()).padStart(2, '0');
    //   const hours = String(date.getHours()).padStart(2, '0');
    //   const minutes = String(date.getMinutes()).padStart(2, '0');
    //   const seconds = String(date.getSeconds()).padStart(2, '0');
    //   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    // },
    handleStockInQuantityInput(event, index) {
      const value = event.target.value;
      console.log('输入的值:', value); // 调试代码
      // 直接更新inCount字段
      this.$set(this.suihuozi, index, { ...this.suihuozi[index], inCount: Number(value) });
      console.log('更新后的值:', this.suihuozi[index].inCount); // 调试代码
    },
    // 处理确定按钮点击事件
    async handleConfirm() {
      // 校验入库数量,大于随货同行单数量,弹窗2秒消失
      for (let item of this.suihuozi) {
        if (item.inCount > item.count) {
          uni.showToast({
            title: '入库数量不能大于发货数量',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }
      // 校验通过，调用updateA方法将数据发送给后端
      await this.updateSuppliersendOrderItem();
	  await this.savePurchaseInOrder();
      // 可以添加其他处理逻辑
	  uni.navigateBack({
	      delta: 1 // 返回的页面层级
	  });
    },
    // 保存采购入库单数据到数据库
    async savePurchaseInOrder() {
      const data = {
        outOrderId: this.product,
        integrateId: this.suihuo.integrateId,
        purchaseOrderId: this.suihuo.purchaseOrderId,
        supplierId: this.suihuo.deptId,
        status: 1,
		dataStatus: 0,
      };
      try {
        await PurchaseInOrderApi.createPurchaseInOrder(data);
        console.log('采购入库单数据保存成功',data);
      } catch (error) {
		  console.log('采购入库单数据保存成功',data);
        console.error('采购入库单数据保存失败:', error);
      }
    },
  //   // 修改一级库台账数据 ,一级库台账信息添加
  //   async taizhangxinzeng() {
  //     console.log('子表数据:', this.suihuozi);
  //     // 采购主单
  //           let caigouzhudata = {};
  //           caigouzhudata.id = this.suihuo.purchaseOrderId;
		// 	caigouzhudata.integrateId = this.suihuo.integrateId;
		// 	caigouzhudata.supplierId = this.suihuo.supplierId;
		// 	caigouzhudata.isMainOrder = 0; 
			
		// 	caigouzhudata.purPurchaseOrderItems = this.suihuozi.map(item => {
		// 	        const subTableItem = this.subTableData.find(subItem => subItem.productId === item.productId);
		// 	        return {
		// 	          purchaseOrderId: this.suihuo.purchaseOrderId,
		// 	          productName: item.productName,
		// 	          productId: item.productId,
		// 	          productUnitId: item.productUnitId,
		// 	          productUnitName: item.productUnitName,
		// 	          productStandards: item.productStandards,
		// 	          productPrice: item.productPrice,
		// 	          totalPrice: item.productPrice * item.inCount, // 使用inCount字段
		// 	          countIn: item.inCount, // 使用inCount字段
		// 	          countOut: item.count - item.inCount,
		// 	          remark: item.remark, // 添加备注
		// 	          inboundBatch: this.getCurrentDateTime(),
		// 	          productCategoryId: item.productCategoryId,
		// 	          productCategoryName: item.productCategoryName,
		// 	          productUnitName: item.productUnitName,
		// 	          productPurchasePrice: item.productPurchasePrice,
		// 	          productUnitId: item.productUnitId
		// 	        };
		// 	      });
      
  //           // 采购单从单数据
  //           let caigoudata = {};
  //           caigoudata.integrateId = this.suihuo.integrateId;
  //           caigoudata.isMainOrder = 0; 
		// 	caigoudata.supplierId = this.suihuo.supplierId;
  //           caigoudata.mainOrderId = this.suihuo.purchaseOrderId;
  //           caigoudata.orderTime = this.formatDate();
  //           console.log("aaaaaaaaa", caigoudata);

  //     let needCreateOrder = false;
  //     const existingProductIds = this.suihuozi.map(item => item.productId);
  //     caigoudata.purPurchaseOrderItems = [
  //       ...this.suihuozi.map(item => {
  //         const subTableItem = this.subTableData.find(subItem => subItem.productId === item.productId);
  //         if (subTableItem && subTableItem.count !== item.inCount) {
  //           needCreateOrder = true;
  //           var inboundBatch = this.getCurrentDateTime();
  //           const newCount = subTableItem.count - item.inCount;
  //           return {
  //             purchaseOrderId: this.suihuo.purchaseOrderId,
  //             productName: item.productName,
  //             productId: item.productId,
  //             productUnitId: item.productUnitId,
  //             productUnitName: item.productUnitName,
  //             productStandards: item.productStandards,
  //             productPrice: item.productPrice,
  //             totalPrice: item.productPrice * item.inCount, // 使用inCount字段
  //             countIn: 0,
  //             countOut: 0,
  //             count: newCount, // 修改为新的count值
  //             remark: item.remark, // 添加备注
  //             inboundBatch: inboundBatch,
  //             productCategoryId: item.productCategoryId,
  //             productCategoryName: item.productCategoryName,
  //             productUnitName: item.productUnitName,
  //             productPurchasePrice : item.productPurchasePrice,
  //             productUnitId : item.productUnitId 
  //           };
  //         }
  //       }).filter(Boolean),
  //       ...this.subTableData.filter(subItem => !existingProductIds.includes(subItem.productId)).map(subItem => {
  //         needCreateOrder = true;
  //         var inboundBatch = this.getCurrentDateTime();
  //         return {
  //           purchaseOrderId: this.suihuo.purchaseOrderId,
  //           productName: subItem.productName,
  //           productId: subItem.productId,
  //           productUnitId: subItem.productUnitId,
  //           productUnitName: subItem.productUnitName,
  //           productStandards: subItem.productStandards,
  //           productPrice: subItem.productPrice,
  //           totalPrice: subItem.productPrice * subItem.count,
  //           countIn: subItem.count,
  //           countOut: 0,
  //           count: subItem.count,
  //           remark: '',
  //           inboundBatch: inboundBatch,
  //           productCategoryId: subItem.productCategoryId,
  //           productCategoryName: subItem.productCategoryName,
  //           productUnitName: subItem.productUnitName,
  //           productPurchasePrice : subItem.productPurchasePrice,
  //           productUnitId : subItem.productUnitId 
  //         };
  //       })
  //     ];

		// console.log('caigouzhudata:', caigouzhudata);
  //     console.log('caigoudata:', caigoudata);
	  

		// await PurPurchaseOrderApi.updateCountPurPurchaseOrder(caigouzhudata);
		
  //     if (needCreateOrder) {
  //       try {
  //         await PurPurchaseOrderApi.createPurPurchaseOrder(caigoudata);
  //         console.log('采购订单创建成功');
  //       } catch (error) {
  //         console.error('采购订单创建失败:', error);
  //       }
  //     }
  //   },
    // 将suihuozi数据发送给后端
    async updateSuppliersendOrderItem() {
      try {
        // 假设后端接口为PurPurchaseOrderApi.updateSuihuozi，根据实际情况修改
        await SupplierSendOrderItemApi.updateSupplierSendOrderItems(this.suihuozi); 
        console.log('数据更新成功',this.suihuozi);
      } catch (error) {
        console.error('数据更新失败:', error);
        throw error; // 抛出错误以便上层处理
      }
    }
  },
};
</script>

<style>
.container {
  padding: 20px;
  background-color: #f5f5f5;
}

.info-card {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-card.horizontal {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-between;
}

.item-field {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.label {
  font-size: 15px;
  color: #333333;
  margin-bottom: 5px;
}

.value {
  font-size: 13px;
  color: #007aff;
}

.button-container {
  margin-top: 20px;
  text-align: center;
}
</style>